"""
题库系统 - 后台管理配置
"""
from django.contrib import admin
from django.utils.html import format_html
from django.db.models import Count, Avg, Sum

from .models import (
    Question, QuestionBank, QuestionBankItem, QuestionTag,
    QuestionTagRelation, QuestionUsageHistory
)


@admin.register(Question)
class QuestionAdmin(admin.ModelAdmin):
    """题目管理"""
    list_display = [
        'title', 'type', 'difficulty', 'subject', 'creator',
        'status', 'usage_count', 'correct_rate_display', 'created_at'
    ]
    list_filter = [
        'type', 'difficulty', 'subject', 'status', 'is_public',
        'review_status', 'created_at'
    ]
    search_fields = ['title', 'stem', 'tags', 'subject', 'chapter']
    readonly_fields = [
        'id', 'usage_count', 'correct_rate', 'created_at', 'updated_at'
    ]

    fieldsets = (
        ('基本信息', {
            'fields': ('title', 'stem', 'type', 'difficulty', 'points', 'time_limit')
        }),
        ('答案选项', {
            'fields': ('options', 'answer', 'analysis', 'explanation')
        }),
        ('分类信息', {
            'fields': ('subject', 'chapter', 'section', 'tags', 'keywords')
        }),
        ('状态控制', {
            'fields': ('is_public', 'status')
        }),
        ('审核信息', {
            'fields': ('review_status', 'reviewer', 'review_comment', 'reviewed_at')
        }),
        ('统计信息', {
            'fields': ('creator', 'usage_count', 'correct_rate', 'created_at', 'updated_at')
        })
    )

    def correct_rate_display(self, obj):
        """显示正确率"""
        if obj.correct_rate is not None:
            percentage = obj.correct_rate * 100
            color = 'green' if percentage >= 70 else 'orange' if percentage >= 40 else 'red'
            return format_html(
                '<span style="color: {};">{:.1f}%</span>',
                color, percentage
            )
        return '-'
    correct_rate_display.short_description = '正确率'

    def get_queryset(self, request):
        return super().get_queryset(request).select_related('creator', 'reviewer')

    def get_readonly_fields(self, request, obj=None):
        if obj:  # 编辑已有对象
            return self.readonly_fields + ['creator']
        return self.readonly_fields


class QuestionBankItemInline(admin.TabularInline):
    """题库题目内联"""
    model = QuestionBankItem
    extra = 0
    readonly_fields = ['added_at', 'effective_points', 'effective_difficulty']
    fields = [
        'question', 'custom_points', 'custom_difficulty',
        'status', 'order', 'effective_points', 'effective_difficulty', 'added_at'
    ]

    def effective_points(self, obj):
        return obj.effective_points
    effective_points.short_description = '有效分数'

    def effective_difficulty(self, obj):
        return obj.effective_difficulty
    effective_difficulty.short_description = '有效难度'


@admin.register(QuestionBank)
class QuestionBankAdmin(admin.ModelAdmin):
    """题库管理"""
    list_display = [
        'name', 'type', 'subject', 'owner', 'question_count_display',
        'total_points', 'is_public', 'created_at'
    ]
    list_filter = [
        'type', 'subject', 'grade_level', 'is_public',
        'allow_export', 'created_at'
    ]
    search_fields = ['name', 'description', 'subject']
    readonly_fields = [
        'id', 'question_count', 'total_points', 'created_at', 'updated_at'
    ]
    inlines = [QuestionBankItemInline]

    fieldsets = (
        ('基本信息', {
            'fields': ('name', 'description', 'type', 'version')
        }),
        ('分类信息', {
            'fields': ('subject', 'grade_level', 'difficulty_range')
        }),
        ('统计信息', {
            'fields': ('question_count', 'total_points'),
            'classes': ('collapse',)
        }),
        ('状态控制', {
            'fields': ('is_public', 'allow_export')
        }),
        ('其他信息', {
            'fields': ('owner', 'last_import_at', 'created_at', 'updated_at'),
            'classes': ('collapse',)
        })
    )

    def question_count_display(self, obj):
        """显示题目数量"""
        count = obj.question_items.filter(status='active').count()
        return f"{count} 题"
    question_count_display.short_description = '题目数量'

    def get_queryset(self, request):
        return super().get_queryset(request).select_related('owner').prefetch_related('question_items')

    def get_readonly_fields(self, request, obj=None):
        if obj:  # 编辑已有对象
            return self.readonly_fields + ['owner']
        return self.readonly_fields


@admin.register(QuestionTag)
class QuestionTagAdmin(admin.ModelAdmin):
    """题目标签管理"""
    list_display = [
        'name', 'category', 'color_display', 'usage_count', 'created_at'
    ]
    list_filter = ['category', 'created_at']
    search_fields = ['name', 'description']
    readonly_fields = ['usage_count', 'created_at']

    def color_display(self, obj):
        """显示颜色"""
        return format_html(
            '<span style="display: inline-block; width: 20px; height: 20px; '
            'background-color: {}; border: 1px solid #ccc;"></span> {}',
            obj.color, obj.color
        )
    color_display.short_description = '颜色'

    def get_queryset(self, request):
        return super().get_queryset(request).annotate(
            question_count=Count('question_relations')
        )


@admin.register(QuestionUsageHistory)
class QuestionUsageHistoryAdmin(admin.ModelAdmin):
    """题目使用历史管理"""
    list_display = [
        'question', 'user', 'usage_type', 'is_correct_display',
        'time_spent_display', 'created_at'
    ]
    list_filter = [
        'usage_type', 'is_correct', 'created_at'
    ]
    search_fields = ['question__title', 'user__username']
    readonly_fields = ['created_at']

    def is_correct_display(self, obj):
        """显示答题结果"""
        if obj.is_correct is True:
            return format_html('<span style="color: green;">正确</span>')
        elif obj.is_correct is False:
            return format_html('<span style="color: red;">错误</span>')
        return '-'
    is_correct_display.short_description = '答题结果'

    def time_spent_display(self, obj):
        """显示用时"""
        if obj.time_spent:
            minutes = obj.time_spent // 60
            seconds = obj.time_spent % 60
            return f"{minutes}分{seconds}秒"
        return '-'
    time_spent_display.short_description = '用时'

    def get_queryset(self, request):
        return super().get_queryset(request).select_related('question', 'user')


# 自定义Admin站点标题
admin.site.site_header = 'AI-SOES 智能在线考试系统'
admin.site.site_title = 'AI-SOES 题库管理'
admin.site.index_title = '题库系统管理后台'